var params = {};
var defaultPageSize = 10;
var currentPage = 1;
var pageSize = defaultPageSize;

var user="用户";
var userGroup="用户组";
var role="角色";

var current = {};

var option = {};

$(function(){
	
	$("ul.tabtit").on("click",changeTab);
	
	loadCurrentPage();

	$('.check').on('click',search);
	
	$('.empty').on('click',emptySearch);
	
	//新增或更新
	$('.add').on('click',add);
});


function loadCurrentPage(){
	var target = "ul.tabtit .current";
	if($(target).text()==userGroup){
    	current.name = userGroup;
    	setUserGroupOption();
    }else if($(target).text()==role){
    	current.name = role;
    	setRoleOption();
    }else if($(target).text()==user){
    	current.name = user;
    	setUserOption();
    }
	loadGrid(option);
}

function changeTab(event){
	var target = event.target;
    if($(target).text()==userGroup){
    	current.name = userGroup;
    	setUserGroupOption();
    }else if($(target).text()==role){
    	current.name = role;
    	setRoleOption();
    }else if($(target).text()==user){
    	current.name = user;
    	setUserOption();
    }
	loadGrid(option);
}

function init(){
	current.name = user;
	
	loadGrid(option);
}

function loadGrid(option){
	params.currentPage = currentPage;
	params.pageSize = pageSize;
	$.ajax({
		url: option.url,
		type:'post',
		data:params
	}).done(function(data){
		var result = data.bo;
		var pager = {};
		option.target.datagrid({
			fitColumns:true,
			singleSelect:true,
			pagination:true,
			remoteSort:false,
			multiSort:true,
			loadMsg:"数据加载中，请稍后……",
			data:result.list,
			columns:[option.columns],
			onSortColumn: function (sort, order) {
				setPager(pager,result.total);
	        }
		});
		
		pager = option.target.datagrid().datagrid('getPager');	// get the pager of datagrid
		setPager(pager,result.total);
		
		//新增或更新
		$('.dealicon').on('click',edit);
		
		//禁用或者启用
		$('.playicon,.disableicon').on('click',changeStatus);
		
		//删除
		$('.delicon').on('click',del);
		
	});
}

function setPager(pager,total){
	pager.pagination({
		total:total,
		pageNumber:currentPage,
	    pageSize:defaultPageSize,
	    layout:['first','prev','links','next','last'],
	    onSelectPage:function(cpage, psize){
	    	currentPage=cpage;
	    	pageSize=psize;
	    	loadGrid(option);
		}
	});
}

function search(){
	var keywords = $('#keywords').val();
	if(keywords!='')
	{
		currentPage = 1;
		pageSize = defaultPageSize;
		if(current.name == userGroup)
		{
			params.likeGroupName = keywords;
		}else if(current.name == role){
			params.likeRoleName = keywords;
		}else if(current.name == user){
			params.username = keywords;
		}
		loadGrid(option);
	}
}

function emptySearch(){
	$('#keywords').val('');
	params = {};
	loadGrid(option);
}

function changeStatus(){
	var id = $(this).attr('row-id');
	var status='';
	var clickStatus = $(this).hasClass("playicon");
	if(clickStatus)//启用
	{
		status = 'Y';
	}else{//禁用
		status = 'N';
	}
	
	var url = "";
	if(current.name == user)
	{
		url = webUrl+'sysUser/updateStatus';
	}else if(current.name == userGroup){
		url = webUrl+'sysGroup/updateStatus';
	}else if(current.name == role){
		url = webUrl+'sysRole/updateStatus';
	}
	
	$.ajax({
		url:url,
		type:'post',
		data:{id:id,status:status}
	}).done(function(data){
		loadGrid(option);
	});
}

function add(){
	var dialog_info = {};
	if(current.name == userGroup)
	{
		dialog_info.title = '新增用户组';
		current.type = "userGroup";
	}else if(current.name == role){
		dialog_info.title = '新增角色';
		current.type = "role";
	}else if(current.name == user){
		dialog_info.title = '新增用户';
		current.type = "user";
	}
	dialog_info.current = current.type;
	dialog_info.yesbtn = '保存';
	saveOrUpdate(dialog_info);
}

function edit(){
	var id = $(this).attr('row-id');
	var dialog_info = {};

	dialog_info.yesbtn = '修改';
	dialog_info.id = id;
	if(current.name == userGroup)
	{
		current.type = "userGroup";
		dialog_info.title = '更新用户组';
		getUserGroupInfoById(id);
	}else if(current.name == role){
		current.type = "role";
		dialog_info.title = '更新角色';
		getRoleInfoById(id);
	}else if(current.name == user){
		current.type = "user";
		dialog_info.title = '更新用户';
		getUserInfoById(id);
	}
	dialog_info.current = current.type;
	saveOrUpdate(dialog_info);
}

function saveOrUpdate(dialog_info){
	new Dialog({
			target:'#'+dialog_info.current+"_dialogbox",
			width:600,
			showYesBtn:true,
			showNoBtn:true,
			title: dialog_info.title,
			yesBtnText:dialog_info.yesbtn,
			noBtnText:'取消',
			yesFn:function(){saveOrUpdateData(this,dialog_info.id)},
			noFn:function(){emptyBox()}}).show();
}

function saveOrUpdateData(obj,id){
	var params = {};
	var flag = true;
	var url;
	//保存用户信息
	if(current.name == user)
	{
		var account = $("#account");
		if(account.val() == '')
		{
			account.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			if(hasName(account.val(),id)){
				account.css({'border-color':'red'});
				flag = false;
				obj.boolConfirm = false;
				$('#existerrormsg').text('已存在');
			}else{
				account.css({'border-color':''});
				$('#existerrormsg').text('');
			}
		}
		
		var username = $("#username");
		if(username.val() == '')
		{
			username.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			username.css({'border-color':''});
		}
		
		var password = $("#password");
		if(password.val() == '')
		{
			password.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			password.css({'border-color':''});
		}
		
		if(flag)
		{
			obj.boolConfirm = true;
			params.id = id;
			params.account = account.val();
			params.username = username.val();
			params.password = password.val();
			params.mobile = $('#mobile').val();
			params.email = $('#email').val();
			var url=webUrl+'sysUser/update';
			if(id==undefined)
			{
				url=webUrl+'sysUser/save';
			}
		}
	}else if(current.name == userGroup){
		var groupname = $("#groupname");
		if(groupname.val() == '')
		{
			groupname.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			if(hasName(groupname.val(),id)){
				groupname.css({'border-color':'red'});
				flag = false;
				obj.boolConfirm = false;
				$('#existerrormsg').text('已存在');
			}else{
				groupname.css({'border-color':''});
				$('#existerrormsg').text('');
			}
		}

		if(flag)
		{
			obj.boolConfirm = true;
			params.id = id;
			params.groupname = groupname.val();
			
			var url=webUrl+'sysGroup/update';
			if(id==undefined)
			{
				url=webUrl+'sysGroup/save';
			}
		}
	}else if(current.name == role){
		var rolename = $("#rolename");
		if(rolename.val() == '')
		{
			rolename.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			if(hasName(rolename.val(),id)){
				rolename.css({'border-color':'red'});
				flag = false;
				obj.boolConfirm = false;
				$('#existerrormsg').text('已存在');
			}else{
				rolename.css({'border-color':''});
				$('#existerrormsg').text('');
			}
		}
		
		var rolecode = $("#rolecode");
		if(rolecode.val() == '')
		{
			rolecode.css({'border-color':'red'});
			flag = false;
			obj.boolConfirm = false;
		}else{
			rolecode.css({'border-color':''});
		}
		
		if(flag)
		{
			obj.boolConfirm = true;
			params.id = id;
			params.rolename = rolename.val();
			params.rolecode = rolecode.val();
			
			var url=webUrl+'sysRole/update';
			if(id==undefined)
			{
				url=webUrl+'sysRole/save';
			}
			
		}
	}
	
	if(flag){
		$.ajax({
			url:url,
			type:'post',
			data:params
		}).done(function(data){
			loadGrid(option);
			emptyBox();
		});
	}
}

function emptyBox(){
	$('input').css({'border-color':''});
	if(current.name == userGroup)
	{
		$("#groupname").val('');
	}else if(current.name == role){
		$("#rolename,#rolecode").val('');
	}else{
		$("#account,#username,#password,#mobile,#email").val('');
	}
}

function getUserInfoById(id){
	$.ajax({
		url:webUrl+'sysUser/get',
		data:{id:id}
	}).done(function(data){
		var result = data.bo;
		$("#account").val(result.account);
		$("#username").val(result.username);
		$("#password").val(result.password);
		$("#mobile").val(result.mobile);
		$("#email").val(result.email);
	});
}

function getUserGroupInfoById(id){
	$.ajax({
		url:webUrl+'sysGroup/get',
		data:{id:id}
	}).done(function(data){
		var result = data.bo;
		$("#groupname").val(result.groupname);
	});
}

function getRoleInfoById(id){
	$.ajax({
		url:webUrl+'sysRole/get',
		data:{id:id}
	}).done(function(data){
		var result = data.bo;
		$("#rolename").val(result.rolename);
		$("#rolecode").val(result.rolecode);
	});
}

function del(){
	var id = $(this).attr('row-id');
	new Dialog({
		target:'#delbox',
		width:300,
		height:160,
		showYesBtn:true,
		showNoBtn:true,
		yesFn:function(){deleteData(id);},
		noFn:function(){}
		}).show();
}

function deleteData(id){
	var url = "";
	if(current.name == user)
	{
		url = webUrl+'sysUser/delete';
	}else if(current.name == userGroup){
		url = webUrl+'sysGroup/delete';
	}else if(current.name == role){
		url = webUrl+'sysRole/delete';
	}

	$.ajax({
		url:url,
		type:'post',
		data:{id:id}
	}).done(function(data){
		console.log('ok');
		loadGrid(option);
	});
}



function setUserOption(){
	option.url = webUrl+'sysUser/pageSysUser';
	option.target = $('#userGrid');
	option.columns = [
			          {field:'_itemNo',title:'序号',align:'center',width:50,formatter:formatId},
			          {field:'username',title:'用户名',width:150,sortable:true},
			          {field:'account',title:'账号',width:150,sortable:true},
			          {field:'mobile',title:'手机',width:200,sortable:true},
			          {field:'email',title:'邮箱',align:'center',width:150,sortable:true},
			          {field:'status',title:'状态',sortable:true,width:150,align:'center',formatter:formatStratus},
			          {field:'lastUpdatedDate',title:'更新时间',width:150,sortable:true,formatter:formatTime},
			          {field:'_operate',title:'操作',width:120,fit:true,align:'center',formatter:formatUserOper},
			      ];
}

function setUserGroupOption(){
	option.url = webUrl+'sysGroup/pageSysUserGroup';
	option.target = $('#userGroupGrid');
	option.columns = [
			          {field:'_itemNo',title:'序号',align:'center',width:50,formatter:formatId},
			          {field:'groupname',title:'用户组',width:150,sortable:true},
			          {field:'status',title:'状态',sortable:true,width:150,align:'center',formatter:formatStratus},
			          {field:'lastUpdatedDate',title:'更新时间',width:150,sortable:true,formatter:formatTime},
			          {field:'_operate',title:'操作',width:120,fit:true,align:'center',formatter:formatGroupOper},
			      ];
}

function setRoleOption(){
	option.url = webUrl+'sysRole/pageSysRole';
	option.target = $('#roleGrid');
	option.columns = [
			          {field:'_itemNo',title:'序号',align:'center',width:50,formatter:formatId},
			          {field:'rolename',title:'角色名',width:150,sortable:true},
			          {field:'rolecode',title:'角色编码',width:150,sortable:true},
			          {field:'status',title:'状态',sortable:true,width:150,align:'center',formatter:formatStratus},
			          {field:'lastUpdatedDate',title:'更新时间',width:150,sortable:true,formatter:formatTime},
			          {field:'_operate',title:'操作',width:120,fit:true,align:'center',formatter:formatRoleOper},
			      ];
}

var formatId = function(val, row,index){
	return (index+1)+(currentPage-1)*pageSize;
}

var formatStratus = function(val){
	if(val=='Y'){
		return '启用';
	}
	return '禁用';
}

var formatTime = function(val){
	if (val != null) {
		var date = new Date(val);
		return date.getFullYear() + '-' + (date.getMonth() + 1) + '-'+ date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
	}
}

var formatUserOper = function(val,row,index){
	var oper = '';
	if(row.status=='N'){
		oper += '<a href="#;" class="playicon tips tipso_style funcbtn update_user_status" row-id="'+row.id+'" data-tipso="启用"></a>';
	}else{
		oper += '<a href="#;" class="disableicon tips tipso_style funcbtn update_user_status" row-id="'+row.id+'" data-tipso="禁用"></a>';
	}
	oper += '<a href="#" class="dealicon tips tipso_style ml10 funcbtn update_user" row-id="'+row.id+'" data-tipso="编辑"></a> <a href="#;" class="delicon tips tipso_style ml10 funcbtn delete_user" row-id="'+row.id+'" data-tipso="删除"></a>';
	return oper;
}

var formatGroupOper = function(val,row,index){
	var oper = '';
	if(row.status=='N'){
		oper += '<a href="#;" class="playicon tips tipso_style funcbtn update_group_status" row-id="'+row.id+'" data-tipso="启用"></a>';
	}else{
		oper += '<a href="#;" class="disableicon tips tipso_style funcbtn update_group_status" row-id="'+row.id+'" data-tipso="禁用"></a>';
	}
	oper += '<a href="#" class="dealicon tips tipso_style ml10 funcbtn update_group" row-id="'+row.id+'" data-tipso="编辑"></a> <a href="#;" class="delicon tips tipso_style ml10 funcbtn delete_group" row-id="'+row.id+'" data-tipso="删除"></a>';
	return oper;
}

var formatRoleOper = function(val,row,index){
	var oper = '';
	if(row.status=='N'){
		oper += '<a href="#;" class="playicon tips tipso_style funcbtn update_role_status" row-id="'+row.id+'" data-tipso="启用"></a>';
	}else{
		oper += '<a href="#;" class="disableicon tips tipso_style funcbtn update_role_status" row-id="'+row.id+'" data-tipso="禁用"></a>';
	}
	oper += '<a href="#" class="dealicon tips tipso_style ml10 funcbtn update_role" row-id="'+row.id+'" data-tipso="编辑"></a> <a href="#;" class="delicon tips tipso_style ml10 funcbtn delete_role" row-id="'+row.id+'" data-tipso="删除"></a>';
	return oper;
}

function hasName(name,id){
	var has = false;
	var url = '';
	var params = {};
	params.name=name;
	params.id=id;
	if(current.name == user)
	{
		url = webUrl+'sysUser/hasAccountSysUser';
	}else if(current.name == userGroup){
		url = webUrl+'sysGroup/hasNameSysUserGroup';
	}else if(current.name == role){
		url = webUrl+'sysRole/hasNameSysRole';
	}

	$.ajax({
		url:url,
		type:'post',
		async:false,
		data:params
	}).done(function(data){
		has = data.bo;
	});
	return has;
}

